import {messages} from "share/common";
import React, {Component} from 'react';
import {Checkbox, Form, Button, Spin, message, Alert, Input, Select, InputNumber, Affix, Switch, Radio} from 'antd'
import {connect} from 'react-redux'
import AccountSettingServer from 'containers/supplier-management/accounting-settings/account-setting-server'
import 'styles/supplier-management/accounting-settings/accounting-settings.scss';
import CompactInput from "components/compact-input";
import CostCenterList from 'containers/supplier-management/accounting-settings/component/cost-center-list'

const Group = Checkbox.Group;
const FormItem = Form.Item;
const InputGroup = Input.Group;
const Option = Select.Option;

@Form.create()
class ConfirmDistribution extends Component {

  constructor(props) {
    super(props);
    this.saveOption = {
      companyOIDs: [],
      tenantId: props.tenant.id,
      artemisEnv: '',
    };
    this.state = {
      loading: false,
      setData: {},// 设置数据
      month: '1',// 当月还是次月
      day: 5,  // 日期 1-28
    }
  }

  componentWillMount() {
    AccountSettingServer(this).getApportionSettingsData({tenantId: this.props.tenant.id}).then(res => {
      if (!res) return;
      let month = '1';
      let day = 5;
      if(res.data.overdueDate){
        const arr = res.data.overdueDate.split('-');
        month = arr[0] != 'undefined' ? arr[0] : '1';
        day = arr[1] != 'undefined' ? arr[1] : 5;
      }
      this.setState({setData: res.data, month, day});
    });
    AccountSettingServer(this).getCompanies().then(res => {
      this.saveOption.companyOIDs = res.data.map(item => {
        return item.companyOID;
      })
    });
    AccountSettingServer(this).getCloudDev().then(res => {
      this.saveOption.artemisEnv = res.data.key;
    })
  }

  // 保存设置
  onSaveSetting = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let costCenterIds = (values['costCenters'] || []).filter(i => !!i).map(i => i.id || i.costCenterId);
        if(costCenterIds.length !== [...new Set(costCenterIds)].length ) {
          message.error(messages('expense-16.key460')/*成本中心不可相同*/);
          return;
        }
        const params = Object.assign({}, values, this.saveOption);
        params.costCenterIds = costCenterIds;
        AccountSettingServer(this).saveApportionSettingsData(params).then(res => {
          message.success(messages('expense-16.key266')/*已保存*/);
        })
      }
    })
  };

  render() {
    const {getFieldDecorator, getFieldValue} = this.props.form;
    const {loading, setData} = this.state;
    const formLayout = {
      labelCol: {span: 4,},
      wrapperCol: {span: 14}
    };
    return (
      <div className='accounting-settings' style={{padding:'16px 20px'}}>
        <div className='alert-position'>
          <Alert
            type='warning'
            message={messages('expense-16.key419')/*启用后，分摊成本中心必须有值，员工以及对账员都无法确认所有成本中心为空的数据。建议您将“生成结算费用的对账状态”配置为员工分发确认或对账确认，否则费用生成后的成本中心修改无法同步至费用*/}
            showIcon
          />
        </div>
        <Spin spinning={loading}>
          <div style={{width: 860,}}>
            <Form  className="new-form">
              <FormItem label={messages('expense-16.key420')/*结算数据及费用分摊*/} {...formLayout}>
                {
                  getFieldDecorator('enable', {
                    initialValue: setData.enable || false,
                    valuePropName: 'checked',
                  })(
                    <Switch />
                  )
                }
              </FormItem>
              {
                getFieldValue('enable') && (
                  <div>
                    <FormItem label={messages('expense-16.key201')/*业务类型*/} {...formLayout}>
                      {
                        getFieldDecorator('vendorTypes', {
                          initialValue: setData.vendorTypes || [],
                          rules: [
                            {required: true, message:messages('expense-16.key274')/*至少选一个*/}
                          ]
                        })(
                          <Group>
                            <Checkbox style={{marginTop: 6}} value='air'>{messages('expense-16.key275')/*机票*/}</Checkbox>
                            <Checkbox value='hotel'>{messages('expense-16.key276')/*酒店*/}</Checkbox>
                            <Checkbox value='train'>{messages('expense-16.key277')/*火车*/}</Checkbox>
                            <Checkbox value='car'>{messages('expense-16.key278')/*用车*/}</Checkbox>
                            <Checkbox value='dining'>{messages('expense-16.key280')/*用餐*/}</Checkbox>
                          </Group>
                        )
                      }
                    </FormItem>
                    <FormItem label={messages('expense-16.key281')/*成本中心*/} {...formLayout} required>
                      {
                        getFieldDecorator('costCenters', {
                          initialValue: setData.costCenters || [],
                          rules: [{
                            validator: (rule, value, callback) => {
                              if(value.filter(i => !!i).length < 1) callback(messages('expense-16.key274')/*至少选一个*/);
                              callback();
                            }
                          }]
                        })(
                          <CostCenterList />
                        )
                      }
                    </FormItem>
                    <FormItem label={messages('expense-16.key421')/*订单成本中⼼映射维度*/} {...formLayout}>
                      {
                        getFieldDecorator('costCenterMapType', {
                          initialValue: setData.costCenterMapType || 'CODE',
                        })(
                          <Radio.Group>
                            <Radio value={'CODE'}>{messages('expense-16.key422')/*成本中心项编码*/}</Radio>
                            <Radio value={'NAME'}>{messages('expense-16.key423')/*成本中心项名称*/}</Radio>
                          </Radio.Group>
                        )
                      }
                    </FormItem>
                  </div>
                )
              }
            </Form>
          </div>
        </Spin>
        <Affix offsetBottom={0} className='setting-fotter-class'>
          <Button
            loading={loading}
            style={{marginLeft: 20}}
            onClick={this.onSaveSetting}
            type='primary'
          >
            {messages('common.save')/*保存*/}
          </Button>
        </Affix>
      </div>
    )
  }
}


function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  }
}

export default connect(mapStateToProps)(ConfirmDistribution);
